package com.geekcoding.geekoj.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.geekcoding.geekoj.entity.Subject;
import com.geekcoding.geekoj.entity.Test;
import com.geekcoding.geekoj.entity.TestStatus;
import com.geekcoding.geekoj.entity.UserEntity;
import com.geekcoding.geekoj.mapper.TestMapper;
import com.geekcoding.geekoj.nums.TestType;
import lombok.NonNull;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.Objects;

@Repository
public class TestRepository extends BaseRepository<Test, Test, TestMapper>{

    @Override
    public Test convert(Test entity) {
        return entity;
    }

    public Test nullOrCreate(@NonNull TestType type, @NonNull Subject subject,  @NonNull UserEntity userEntity) {
        LambdaQueryWrapper<Test> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(Test::getAnswerId, userEntity.getId())
                .eq(Test::getType, type)
                .eq(Test::getState, TestStatus.INIT)
                .eq(Test::getSubjectId, subject.getId());
        Test test = baseMapper.selectOne(lambdaQuery);
        if(Objects.isNull(test)){
            test = createTest(subject.getId(), type, userEntity);
        }
        return test;
    }

    private Test createTest(String subjectId, TestType type, UserEntity userEntity) {
        Test test = Test.builder()
                .answerId(userEntity.getId())
                .type(type)
                .createTime(new Date())
                .answerTime(new Date())
                .subjectId(subjectId)
                .state(TestStatus.INIT)
                .build();
        baseMapper.insert(test);
        return test;
    }
}
